<template>
  <a-modal :visible="visible" :title="title" centered width="448px" @ok="$emit('ok', dates)" @cancel="$emit('cancel')">
    <div class="calendar-container" :style="{ width: '400px', border: '1px solid #d9d9d9', borderRadius: '4px' }">
      <a-calendar :fullscreen="false">
        <template slot="dateFullCellRender" slot-scope="value">
          <div :class="['date-text', dates.includes(value.format('YYYY-MM-DD')) ? 'selected' : '']" @click="handleSelect(value)">
            {{ $moment(value).format('DD') }}
          </div>
        </template>
      </a-calendar>
    </div>
  </a-modal>
</template>

<script>
export default {
  name: 'CalendarPicker',
  props: {
    visible: {
      type: Boolean,
      default: false
    },

    title: {
      type: String,
      default: '选择日期'
    },

    defaultDates: {
      type: Array,
      default: () => []
    }
  },

  data () {
    return {
      dates: []
    }
  },

  watch: {
    visible (bool) {
      if (!bool) this.$nextTick(_ => this.dates.splice(0))
    },

    defaultDates: {
      handler  (arr) {
        const { dates } = this
        dates.splice(0, dates.length, ...arr)
        this.$forceUpdate()
      },
      immediate: true,
      deep: true
    }
  },

  methods: {
    handleSelect (date) {
      date = date.format('YYYY-MM-DD')
      const { dates, $moment } = this
      const index = dates.indexOf(date)
      if (index > -1) dates.splice(index, 1)
      else {
        dates.push(date)
        dates.sort((a, b) => $moment(a).isAfter(b) ? 1 : -1)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.calendar-container {
  /deep/ .ant-fullcalendar-header {
    /deep/ .ant-radio-group.ant-radio-group-outline {
      display: none;
    }
  }

  /deep/ .ant-fullcalendar-last-month-cell,
  /deep/ .ant-fullcalendar-next-month-btn-day {
    .date-text {
      color: gray;
      opacity: .5;

      &.selected {
        color: lightgrey;
        opacity: .75;
      }
    }
  }

  /deep/ .ant-fullcalendar-cell {
    cursor: pointer;
  }
}

.date-text {
  .Flex;
  .Flex-center;

  &.selected {
    background: @blue;
    color: #fff;
  }
}
</style>
